package com.eastfair.imaster.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.base.SubjectTypeEnum;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.code.ExceptionCode;
import com.eastfair.echo.core.EchoService;
import com.eastfair.enums.AuditStateEnum;
import com.eastfair.imaster.dto.AppointmentDTO;
import com.eastfair.imaster.dto.AppointmentPageQuery;
import com.eastfair.imaster.dto.AppointmentSaveDTO;
import com.eastfair.imaster.dto.AppointmentUpdateDTO;
import com.eastfair.imaster.entity.Appointment;
import com.eastfair.imaster.service.AppointmentService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 邀约
 * </p>
 *
 * @author liuxiaobai
 * @date 2021-09-02
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/appointment")
@Api(value = "Appointment", tags = "邀约")
public class AppointmentController extends SuperController<AppointmentService, Long, Appointment, AppointmentPageQuery, AppointmentSaveDTO, AppointmentUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Override
    public void handlerResult(IPage<Appointment> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Appointment> appointmentList = list.stream().map((map) -> {
            Appointment appointment = Appointment.builder().build();
            //TODO 请在这里完成转换
            return appointment;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(appointmentList));
    }

    /**
     * 批量发起邀约
     * @param appointmentDTO receiveIds
     * @return boolean
     */
    @PostMapping("/launchBatch")
    public R<Boolean> launchBatch(@RequestBody @Validated AppointmentDTO appointmentDTO) {
        if (appointmentDTO.getReceiveIds() == null || appointmentDTO.getReceiveIds().isEmpty()) {
            return fail(ExceptionCode.ILLEGAL_ARGUMENT_EX);
        }
        return this.baseService.launchBatch(appointmentDTO);
    }

    /**
     * 查询当前登录人待处理邀约请求数量
     * @return int
     */
    @PostMapping("/getPendingNum")
    public R<Integer> getPendingNum() {
        Long currentUserId = ContextUtil.getUserId();
        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Appointment::getProjectId,ContextUtil.getProjectId())
                .eq(Appointment::getExhibitionId,ContextUtil.getExhibitionId())
                .eq(Appointment::getStatus, AuditStateEnum.PENDING.name())
                .eq(Appointment::getIsDelete, BusinessConstant.DELETE_NO);
        if (SubjectTypeEnum.ACTOR.name().equals(ContextUtil.getSubjectType())) {
            queryWrapper.lambda()
                    //todo 获取当前登录人所属展商ID
                    .eq(Appointment::getExhibitorId,1L)
                    //对接员工为自己或无对接员工
                    .and(wrapper -> wrapper
                            .eq(Appointment::getEmployeeUserId,currentUserId)
                            .or()
                            .isNull(Appointment::getEmployeeUserId));
        } else {
            queryWrapper.lambda().eq(Appointment::getVisitorUserId,currentUserId);
        }
        return success(this.baseService.count(queryWrapper));
    }

    /**
     * 同意/拒绝
     * @param appointmentDTO id status
     * @return boolean
     */
    @PostMapping("/changeStatus")
    public R<Boolean> changeStatus(@RequestBody AppointmentDTO appointmentDTO) {
        if (appointmentDTO.getId() == null || StrUtil.isEmpty(appointmentDTO.getStatus())) {
            return fail(ExceptionCode.ILLEGAL_ARGUMENT_EX);
        }
        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Appointment::getProjectId,ContextUtil.getProjectId())
                .eq(Appointment::getId,appointmentDTO.getId())
                .eq(Appointment::getIsDelete,BusinessConstant.DELETE_NO);
        Appointment appointment = this.baseService.getOne(queryWrapper,false);
        if (appointment == null) {
            return fail(ExceptionCode.NOT_FOUND);
        }
        //校验数据所属权
        if (SubjectTypeEnum.VISITOR.name().equals(ContextUtil.getSubjectType())
                && !ContextUtil.getUserId().equals(appointment.getVisitorUserId())) {
            return fail(ExceptionCode.OPERATION_EX);
        } else if (SubjectTypeEnum.ACTOR.name().equals(ContextUtil.getSubjectType())
                && !ContextUtil.getUserId().equals(appointment.getEmployeeUserId())) {
            return fail(ExceptionCode.OPERATION_EX);
        }
        return success(this.baseService.updateStatus(appointmentDTO));
    }
}
